<template>
  <!-- 搜索 -->
  <el-card style="height: 80px">
    <search-comp
      :label="label"
      @handleSearch="handleSearch"
      @handleReset="handleReset"
    />
  </el-card>
  <!-- 表单 -->
  <el-card style="margin: 10px 0px">
    <el-button
      icon="Plus"
      v-if="hasPermission('sys:user:add')"
      type="primary"
      size="default"
      @click="addUser"
      >添加用户</el-button
    >
    <!-- table展示用户信息 -->
    <el-table style="margin: 10px 0px" :data="userArr" stripe>
      <el-table-column type="selection"></el-table-column>
      <el-table-column label="ID" prop="id"></el-table-column>
      <el-table-column
        label="用户姓名"
        prop="name"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="用户昵称"
        prop="nickName"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="用户机构"
        prop="deptName"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="角色"
        prop="roleNames"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="邮箱"
        prop="email"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="手机"
        prop="mobile"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column label="状态" prop="status" show-overflow-tooltip>
        <template #default="scope">
          {{ scope.row.status === 0 ? "禁用" : "正常" }}
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        fixed="right"
        width="150px"
        v-if="
          hasPermission('sys:user:edit') || hasPermission('sys:user:delete')
        "
      >
        <template #default="scope">
          <el-button
            type="primary"
            v-if="hasPermission('sys:user:edit')"
            link
            size="small"
            icon="Edit"
            @click="updateUser(scope.row)"
            >编辑</el-button
          >
          <el-popconfirm
            :title="`你确定要删除${scope.row.name}?`"
            width="260px"
            @confirm="deleteUser(scope.row.id)"
          >
            <template #reference>
              <el-button
                link
                type="danger"
                v-if="hasPermission('sys:user:delete')"
                size="small"
                icon="Delete"
                >删除</el-button
              >
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
  <!-- 分页 -->
  <el-card>
    <pagination
      :pageNum="pageNum"
      :pageSize="pageSize"
      :total="total"
      @handleCurrentChange="handleCurrentChange"
      @handleSizeChange="handleSizeChange"
    />
  </el-card>
  <!-- 新增或者编辑 -->
  <drawer
    ref="drawerUserRef"
    @cancel="handleCancelUser"
    @submit="handleSubmitUser"
  >
    <template v-slot:title>
      <h4>{{ userParams.id ? "更新用户" : "添加用户" }}</h4>
    </template>
    <template v-slot:content>
      <el-form
        ref="formRef"
        label-width="auto"
        :model="userParams"
        :rules="rules"
      >
        <el-form-item label="用户姓名" prop="name">
          <el-input
            placeholder="请您输入用户姓名"
            v-model="userParams.name"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickName">
          <el-input
            placeholder="请您输入用户昵称"
            v-model="userParams.nickName"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password" v-if="!userParams.id">
          <el-input
            placeholder="请您输入用户密码"
            v-model="userParams.password"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户机构" prop="deptName">
          <popup-tree-input
            :data="deptData"
            :nodeKey="'' + userParams.deptId"
            :prop="userParams.deptName"
            @handleCurrentChange="handleCurrentChanges"
          ></popup-tree-input>
        </el-form-item>
        <el-form-item label="用户邮箱" prop="email">
          <el-input
            v-model="userParams.email"
            placeholder="请您输入用户邮箱"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input
            v-model="userParams.mobile"
            placeholder="请您输入手机号码"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="userRoles" v-if="userParams.id">
          <el-select
            v-model="userParams.userRoles"
            collapse-tags
            multiple
            placeholder="请选择用户角色"
            style="width: 100%"
          >
            <el-option
              v-for="item in roles"
              :key="item.id"
              :label="item.remark"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </template>
  </drawer>
</template>
<script setup lang="ts">
import { onMounted, ref, reactive, nextTick } from "vue";
import type {
  Records,
  IUserResponseData,
  IUser,
  IPage,
  Roles,
  Depts,
} from "@/api/acl/type";
import { reqUserList, reqAddOrUpdateUser, reqDeleteUser } from "@/api/acl/user";
import { reqRoleFindAll } from "@/api/acl/role";
import { reqDeptFindTree } from "@/api/acl/dept";
import { ElMessage } from "element-plus";
import { hasPermission } from "@/utlis/permission";
import {
  validatorName,
  validatorNickName,
  validatorPassword,
  validatorEmail,
  validatorMobile,
} from "@/utlis/validator";
//默认页码
const pageNum = ref<number>(1);
//一页展示几条数据
const pageSize = ref<number>(5);
//用户总个数
const total = ref<number>(0);
//搜索条件
const keyword = ref<string>("");
//存储全部用户的数组
const userArr = ref<Records>([]);
const label = ref<string>("用户名");
const drawerUserRef = ref();
//收集用户信息的响应式数据
const userParams = reactive<IUser>({
  name: "",
  nickName: "",
  password: "",
  deptName: "",
  email: "",
  mobile: "",
  userRoles: [],
  deptId: 1,
  status: 1,
});
//获取form组件实例
const formRef = ref<any>();
onMounted(() => {
  inintData();
});
//搜索
const handleSearch = (val: string) => {
  keyword.value = val;
  pageNum.value = 1;
  inintData();
};
//重置搜索
const handleReset = () => {
  keyword.value = "";
  pageNum.value = 1;
  inintData();
};
//分页器下拉菜单的自定义事件的回调
const handleCurrentChange = (val: number) => {
  pageNum.value = val;
  inintData();
};
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  inintData();
};
const inintData = async () => {
  const perams: IPage = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    params: {
      name: keyword.value,
    },
  };
  const res: IUserResponseData = await reqUserList(perams);
  if (res.code == 200) {
    total.value = res.data.totalSize;
    userArr.value = res.data.content;
  }
};

//添加
const addUser = () => {
  drawerUserRef.value.open();
  //清空数据
  Object.assign(userParams, {
    id: undefined,
    name: "",
    nickName: "",
    password: "",
    deptName: "",
    email: "",
    mobile: "",
    userRoles: [],
    deptId: 1,
    status: 1,
  });
  findUserRoles();
  findDeptTree();
};
//关闭
const handleCancelUser = () => {
  drawerUserRef.value.close();
};
//保存
const handleSubmitUser = async () => {
  //点击保存按钮的时候,务必需要保证表单全部复合条件在去发请求
  await formRef.value.validate();
  //按钮加载
  drawerUserRef.value.showloading();
  let params: any = Object.assign({}, userParams);
  //保存按钮:添加新的用户|更新已有的用户账号信息
  let userRoles = [];
  if (userParams.id) {
    for (let i = 0, len = params.userRoles.length; i < len; i++) {
      let userRole = {
        userId: params.id,
        roleId: params.userRoles[i],
      };
      userRoles.push(userRole);
    }
    params.userRoles = userRoles;
  }
  const res = await reqAddOrUpdateUser(params);
  //添加或者更新成功
  if (res.code == 200) {
    //关闭抽屉
    handleCancelUser();
    //提示消息
    ElMessage({
      type: "success",
      message: userParams.id ? "编辑成功" : "添加成功",
    });
    drawerUserRef.value.hideloading();
    //获取最新的全部账号的信息
    pageNum.value = 1;
    inintData();
  } else {
    //关闭抽屉
    handleCancelUser();
    //提示消息
    ElMessage({
      type: "error",
      message: userParams.id ? "编辑失败" : "添加失败",
    });
    drawerUserRef.value.hideloading();
  }
};
//编辑
const updateUser = (row: any) => {
  //抽屉显示出来
  addUser();
  //存储收集已有的账号信息
  Object.assign(userParams, row);
  let userRole = [];
  for (let i = 0, len = row.userRoles.length; i < len; i++) {
    userRole.push(row.userRoles[i].roleId);
  }
  userParams.userRoles = userRole;
  console.log(userParams);
  //清除上一次的错误的提示信息
  nextTick(() => {
    formRef.value.clearValidate("name");
    formRef.value.clearValidate("nickName");
    formRef.value.clearValidate("password");
    formRef.value.clearValidate("email");
    formRef.value.clearValidate("mobile");
  });
};

//删除
const deleteUser = async (id: any) => {
  let params = [];
  let idArray = (id + "").split(",");
  for (let i = 0; i < idArray.length; i++) {
    params.push({ id: idArray[i] });
  }
  const res = await reqDeleteUser(params);
  if (res.code === 200) {
    ElMessage({
      type: "success",
      message: "删除成功",
    });
    inintData();
  } else {
    ElMessage({
      type: "error",
      message: res.msg,
    });
  }
};
//表单校验的规则对象
const rules = {
  //用户名字
  name: [{ required: true, trigger: "blur", validator: validatorName }],
  //用户昵称
  nickName: [{ required: true, trigger: "blur", validator: validatorNickName }],
  //用户的密码
  password: [{ required: true, trigger: "blur", validator: validatorPassword }],
  //用户的邮箱
  email: [{ required: true, trigger: "blur", validator: validatorEmail }],
  //用户的手机号
  mobile: [{ required: true, trigger: "blur", validator: validatorMobile }],
};
//加载用户角色
const roles = ref<Roles>([]);
const findUserRoles = async () => {
  // 加载角色集合
  const res = await reqRoleFindAll();
  if (res.code === 200) {
    roles.value = res.data;
  }
};

//获取部门列表
const deptData = ref<Depts>([]);
const findDeptTree = async () => {
  const res = await reqDeptFindTree();
  deptData.value = res.data;
};
// 菜单树选中
const handleCurrentChanges = (data: any) => {
  userParams.deptId = data.id;
  userParams.deptName = data.name;
};
</script>
<style lang="scss" scoped></style>
